#include "tools/list.h"
#include "tools/log.h"
void list_init(list_t * list)
{
    list->first = list->last = 0;
    list->count = 0;
}

// 链表头插
void list_insert_first(list_t * list, list_node_t * node)
{
    node->next = list->first;
    node->pre = 0;  

    if(list_is_empty(list))
    {
        list->first = list->last = node;
    }
    else
    {
        list->first->pre = node;
        list->first = node;
    }
    list->count++;
}

// 链表尾插
void list_insert_last(list_t * list, list_node_t * node)
{
    node->pre = list->last;
    node->next = 0;

    if(list_is_empty(list))
    {
        list->first = list->last = node;
    }
    else
    {
        list->last->next = node;
        list->last = node;
    }
    list->count++;
}

// 链表头删
list_node_t * list_remove_first(list_t * list)
{
    if(list_is_empty(list)) return 0;
    list_node_t * remove_node = list->first;
    list->first = remove_node->next;
    if(list->first)
    {
        list->first->pre = 0;
    }
    else
    {
        list->last = 0;
    }
    remove_node->next = 0;
    list->count--;   
    return remove_node;
}

// 链表删除特定节点
list_node_t * list_remove_node(list_t * list, list_node_t * node)
{
    if(!node) return 0;
    if(node == list->first) list->first = node->next;
    if(node == list->last) list->last = node->pre;

    if(node->pre) node->pre->next = node->next;
    if(node->next) node->next->pre = node->pre;

    node->next = node->pre = 0;
    list->count--;
    return node;
}